<template>
  <div>
    <form-create
        v-model="fApi"
        :rule="rule"
        :option="option"
        style="margin: 30px;"
    ></form-create>
  </div>
</template>

<script>
  import formCreate from "@form-create/element-ui";
  import {selectById} from '../form/api'

  export default {
    name:'TmptDynamicForm',
    props:{
      dynamicFormId: {
        type: String
      },
      param: {
        type: Object,
        default: ()=>{}
      },
    },
    data () {
      return {
        fApi: null,
        rule:[],
        option:{},
        isOutLink: false //是否直接超链接，http://localhost:8080/testadmin/#/tmptDynamicForm?dynamicFormId=4
      }
    },
    watch:{
      param:{
        handler(val) {
          console.log('---- new page ----')
          console.log(this.param)
          console.log(val)
          this.initFormSheet()
        },
        immediate: true,
        deep: true
      }
    },
    mounted() {
    },
    methods: {
      getFApi() {
        return this.fApi
      },
      getElVm(fieldId) {
        const vm = this.fApi.el(fieldId)
        return vm
      },
      // 通过 dynamicFormId 自动加载新的表单页面
      async initFormSheet() {
        if (this.dynamicFormId) {
          this.isOutLink=false
        }else{
          this.isOutLink=true
        }

        let dynamicFormId = this.dynamicFormId
        console.log('dynamicFormId')
        console.log(dynamicFormId)
        // 单独的页面运行
        // http://localhost:8080/testadmin/#/tmptDynamicForm?dynamicFormId=4
        if (this.isOutLink&&this.$route&&this.$route.query&&this.$route.query.dynamicFormId) {
          dynamicFormId = this.$route.query.dynamicFormId
          // query里参数，存入store中，所有api调用时，一起发给后端，参数中有token, 可用作身份验证
          // await this.$store.commit('taskflowBusinessData/setQueryData', this.$route.query)
        }
        console.log(dynamicFormId)
        const result = await selectById({"id":dynamicFormId})
        if (!result.success) {
          this.notify(result)
          return
        }
        this.rule =  formCreate.parseJson(result.obj.rule)
        this.option = formCreate.parseJson(result.obj.option)

        // 等页面渲染显示出来后，加载数据内容
        console.log('自动加载参数this.param')
        console.log(this.param)
        this.$nextTick(()=>{
          const fields = this.fApi.fields()
          console.log(fields)
          fields.forEach(fieldId=>{
            // 找组件 loadDataAuto，并调用其 loadData(), 完成数据加载
            const vm = this.fApi.el(fieldId)
            const formCreateInject = vm.formCreateInject
            if (formCreateInject && formCreateInject.prop.type==='loadDataAuto') {
              vm.loadData(this.param)
            }

          })
        })

      },
    }
  }
</script>
